#include"chainlist.h"
#include <stdio.h>
#include <stdlib.h>

//初始化链表
void initChainList(ChainList_t *table) {
    table->header= NULL;
    table->count=0;
}
//释放表中的所有节点
void destroyChainList(ChainList_t *table) {
        node_t dummy;
        dummy.next = table->header;

        node_t *p=&dummy;
        while(p->next!=NULL) {
            node_t *temp = p->next;
            p->next = temp->next;
            free(temp);
        }
        table->header=NULL;
}
//头插
int insertChainListHead(ChainList_t *table, Element_t value) {
    //使用dummy节点就是创造一个临时的头节点
    node_t dummy;
    dummy.next = table->header;

    node_t *p=&dummy;
    node_t *new_node=malloc(sizeof(node_t));
    if (new_node == NULL) { //新节点分配失败
        fprintf(stderr, "Error allocating memory for new_node\n");
        return -1;
    }

    new_node->val = value;
    new_node->next = p->next;
    p->next = new_node;

    table->count++;
    //跟新表头中的头指针
    table->header = dummy.next;
    return 0;
}
//任意位置插入
int insertChainListPos(ChainList_t *table, int pos, Element_t value) {
    node_t dummy;
    dummy.next = table->header;

    //插入位置合理性检查
    if (pos < 0 || pos > table->count) {
        printf("pos is out of range\n");
        return -1;
    }

    node_t *p=&dummy;
    int index=-1;//头节点的位置是-1
    while (index<pos-1) {//找到插入位置的前一个节点
        p=p->next;
        index++;
    }

    node_t *new_node=malloc(sizeof(node_t));
    if (new_node == NULL) { fprintf(stderr, "Error allocating memory for new_node\n");return -1;}

    new_node->val = value;
    new_node->next = p->next;
    p->next = new_node;
    table->count++;

    table->header = dummy.next;
    return 0;
}


//删除指定值的节点
int deleteChainListValue(ChainList_t *table, Element_t value) {
    node_t dummy;
    dummy.next = table->header;

    node_t *p=&dummy;
    while (p->next!=NULL) {
      if(p->next->val==value) break;
      p=p->next;
      }
     if(p->next==NULL){
        printf("value is not found\n");
        return -1;
     }
    node_t *temp=p->next;
    p->next = temp->next;
    free(temp);
    table->count--;

    table->header = dummy.next;
    return 0;
}

//打印链表
void showChainList(const ChainList_t *table) {
   node_t *p=table->header;
    printf("ChainList's size is %d\n", table->count);
   while (p!=NULL) {
        printf("%d\t", p->val);
        p=p->next;
   }
   printf("\n");
}

